/**
 * 遮罩层mixin 目前只完成一级遮罩层
 */

let createElement = (id) => {
	let div_modal = document.createElement('div');
	let instance = MaskManage.maskObj[id];
	div_modal.className = 'mask';
	div_modal.setAttribute('id', id);
	document.body.appendChild(div_modal);

	div_modal.addEventListener('click', () => {
		instance.close();
	});

	div_modal.addEventListener('touchmove', (event) => {
		event.preventDefault();
		event.stopPropagation();
	});
};

let removeElement = (id) => {
	let div_modal = document.getElementById(id);
	document.body.removeChild(div_modal);
};

let MaskManage = {
	maskId: 0,
	maskObj: {},
	maskList: [],
	registe: (id, instance) => {
		MaskManage.maskObj[id] = instance;
	},
	unregiste: (id) => {
		MaskManage.maskObj[id] = null;
		delete MaskManage.maskObj[id];
	},
	openMask: (id) => {
		// TODO:
		// console.log(this); //console: undefined？
		MaskManage.maskList.push({ id });
		createElement(id);
	},
	closeMask: (id) => {
		removeElement(id);
	}
};

export default {
	name: 'modal-mixin',
	props: {
		'value': {
			type: Boolean,
			default: false
		},
		'useMask': {
			type: Boolean,
			default: true
		},
		'closeOnClickMask': {
			type: Boolean,
			default: true
		}
	},
	beforeDestroy () {
		if (MaskManage.maskList.length > 0) {
			let cur_mask = MaskManage.maskList.pop();
			MaskManage.closeMask(cur_mask.id);
		}
		MaskManage.maskObj = {};
		MaskManage.maskList = [];
	},
	watch: {
		value (val, oldVal) {
			if (val) {
				this.open();
			}
			else {
				this.close();
			}
		}
	},
	methods: {
		open () {
			if (this.useMask) {
				this.$emit('input', true);
				let id = 'mask_' + MaskManage.maskId++;
				MaskManage.registe(id, this);
				MaskManage.openMask(id);
			}
		},
		close () {
			if (this.useMask && this.closeOnClickMask) {
				this.$emit('input', false);
				// 如果是点击遮罩层关闭，此时this.value还是true，正常情况下应该先改变value
				if (this.value) {
					return;
				}
				let cur_mask = MaskManage.maskList.pop();
				MaskManage.unregiste(cur_mask.id);
				MaskManage.closeMask(cur_mask.id);
			}
		}
	},
	mounted () {
		if (this.value) {
			this.open();
		}
	}
};
